from pymodbus.client.sync import ModbusTcpClient

try:
    from pymodbus.client.sync import ModbusTcpClient
    print("pymodbus 导入成功")
except ImportError:
    print("pymodbus 导入失败，请检查安装")

# 连接到Modbus服务器
client = ModbusTcpClient('localhost', port=502)
if client.connect():
    # 读取保持寄存器
    result = client.read_holding_registers(address=0, count=10)
    if not result.isError():
        print(result.registers)
    else:
        print(f"读取失败: {result}")
    client.close()
else:
    print("连接失败")